package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constans.wemedia.WemediaContans;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dto.WmMaterialDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.MaterialService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class MaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial>implements MaterialService {
    @Autowired
    FastDFSClient fastDFSClient;
    @Value("${fdfs.url}")
    String fileServerUrl;
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1. 检查参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2. 封装条件   分页条件   查询条件
        Page<WmMaterial> pageRequest = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = Wrappers.<WmMaterial>lambdaQuery();
        if(dto.getIsCollected()!=null && dto.getIsCollected().equals(WemediaContans.COLLECT_MATERIAL)){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,WemediaContans.COLLECT_MATERIAL);
        }
        //3. 执行查询
        IPage<WmMaterial> pageResult = page(pageRequest, lambdaQueryWrapper);

        List<WmMaterial> list = pageResult.getRecords();
        list = list.stream().map((item) -> {  // 对每一个元素进行处理
            item.setUrl(fileServerUrl + item.getUrl()); // 添加前缀路径
            return item;
        }).collect(Collectors.toList()); // 将所有处理号的素材收集到一个新的集合中
        ResponseResult responseResult = new PageResponseResult(pageRequest.getCurrent(),pageRequest.getSize(),pageResult.getTotal());
        responseResult.setData(list);
        return responseResult;
    }
    @Autowired
   private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult delPicture(Integer id) {
        //检查参数
     if(id==null){
         return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
     }
        //判断当前图片是否被引用
        Integer count = wmNewsMaterialMapper.selectCount(
                Wrappers.<WmNewsMaterial>lambdaQuery()
                        .eq(WmNewsMaterial::getMaterialId, id)
        );
     if(count!=null && count>0){
         return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前素材以引用，不可删除");
     }
     //获取当前登录用户
        WmUser user = WmThreadLocalUtils.getUser();
     if(user==null){
         return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
     };
     //根据id和当前登录用户id查询出素材
        WmMaterial wmMaterial = getOne(Wrappers.<WmMaterial>lambdaQuery()
                .eq(WmMaterial::getId, id)
                .eq(WmMaterial::getUserId, user.getId())
        );
        //根据素材获取文件路径
        fastDFSClient.delFile(wmMaterial.getUrl());
        removeById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //检查参数
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //更新状态
        Integer uid = WmThreadLocalUtils.getUser().getId();
        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,type)
        .eq(WmMaterial::getId,id)
        .eq(WmMaterial::getUserId,uid));

        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }
}
